package 力扣_链表.基础操作;

/**
 * @author zx
 * @create 2022-08-15 15:32
 */
public class 链表中倒数第k个节点_Oferr22 {
    /**
     * @return 快慢指针
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0;i < k;i++){
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    /**
     * @return 暴力解法
     */
    public ListNode getKthFromEnd2(ListNode head, int k) {
        ListNode temp = head;
        int count = 0;
        while(temp != null){
            count++;
            temp = temp.next;
        }
        count = count - k;
        while(head != null && count > 0){
            count--;
            head = head.next;
        }
        return head;
    }
}
